<!--
 * @Description: 编辑技-师
 * @Author: DXV-RGWU-TUFH-RFCY-IEGMYY
 * @Date: 2021-07-03 11:41:05
 * @LastEditTime: 2023-05-26 18:21:19
 * @LastEditors: DXV-RGWU-TUFH-RFCY-IEGMYY
-->

<template>
  <div class="lb-technician-edit">
    <top-nav :title="navTitle" :isBack="true" />
    <div class="page-main">
      <el-form @submit.native.prevent :model="subForm" ref="subForm" :rules="subFormRules" label-width="130px">
        <el-form-item label="关联用户" prop="user_id">
          <el-tag class="cursor-pointer" :type="have_user_id ? 'info' : 'primary'"
            @click="toShowDialog">{{ subForm.user_id ? subForm.nickName : '选择关联用户' }}</el-tag>
        </el-form-item>
        <el-form-item :label="$t('action.attendantName') + '姓名'" prop="coach_name">
          <el-input v-model="subForm.coach_name" maxlength="15" show-word-limit
            :placeholder="'请输入' + $t('action.attendantName') + '姓名'"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="subForm.sex">
            <el-radio :label="0">男</el-radio>
            <el-radio :label="1">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="生日" prop="birthday">
          <el-date-picker v-model="subForm.birthday" type="date" placeholder="请选择日期" value-format="timestamp"
            :picker-options="pickerOptions"></el-date-picker>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="subForm.mobile" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="从业年份" prop="work_time">
          <el-input v-model.number="subForm.work_time" placeholder="请输入从业年份"></el-input>
        </el-form-item>
        <el-form-item label="意向工作城市" prop="city_id">
          <el-select v-model="subForm.city_id" placeholder="请选择">
            <el-option v-for="item in base_city" :key="item.id" :label="item.title" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属经纪人" prop="" v-if="subForm.partner_id && subForm.partner_name">
          <div>{{ subForm.partner_name }}</div>
        </el-form-item>
        <el-form-item label="所属代理商" prop="" v-if="subForm.admin_id && subForm.admin_name">
          <div>{{ subForm.admin_name }}</div>
        </el-form-item>
        <el-form-item label="挂靠门店" prop="store_id" v-if="
            routesItem.auth.store &&
            (!subForm.id || (subForm.admin_id && base_store.length > 0))
          ">
          <el-select @change="changeStore" v-model="subForm.store_id" filterable clearable placeholder="请选择">
            <el-option v-for="item in base_store" :key="item.id" :label="item.title" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所在地址" prop="address">
          <el-input v-model="subForm.address" placeholder="请输入所在地址"></el-input>
        </el-form-item>
        <el-form-item label="经度" prop="lng">
          <el-input v-model="subForm.lng" placeholder="请输入经度"></el-input>
        </el-form-item>
        <el-form-item label="纬度" prop="lat">
          <el-input v-model="subForm.lat" placeholder="请输入纬度"></el-input>
          <lb-button @click="showMap = true" type="primary" plain size="mini">获取经纬度</lb-button>
        </el-form-item>
        <el-form-item :label="$t('action.attendantName') + '简介'" prop="text">
          <el-input type="textarea" :rows="10" maxlength="300" resize="none" show-word-limit
            :placeholder="'请输入' + $t('action.attendantName') + '简介'" v-model="subForm.text"></el-input>
        </el-form-item>
        <el-form-item label="身份证号" prop="id_code">
          <el-input v-model="subForm.id_code" placeholder="请输入身份证号"></el-input>
        </el-form-item>
        <el-form-item label="身份证照片" prop="id_card">
          <lb-cover :fileList="subForm.id_card" fileType="image" type="more"
            @selectedFiles="getBannerList($event, 'id_card')" :fileSize="3"></lb-cover>
          <lb-tool-tips>请分别上传身份证人像面、身份证国徽面、手持身份证照片</lb-tool-tips>
        </el-form-item>
        <!-- <el-form-item label="资格证书" prop="license">
          <lb-cover :fileList="subForm.license" fileType="image" type="more"
            @selectedFiles="getBannerList($event, 'license')" :fileSize="15"></lb-cover>
        </el-form-item> -->
        <el-form-item label="工作形象照" prop="work_img">
          <lb-cover :fileList="subForm.work_img" @selectedFiles="getCover($event, 'work_img')"></lb-cover>
          <lb-tool-tips>图片建议尺寸: 750 * 750</lb-tool-tips>
        </el-form-item>
        <el-form-item label="个人生活照" prop="self_img">
          <lb-cover :fileList="subForm.self_img" fileType="image" type="more" tips="750 * n"
            @selectedFiles="getBannerList($event, 'self_img')" :fileSize="9"></lb-cover>
        </el-form-item>

        <!-- <el-form-item label="个人视频介绍" prop="video">
          <div class="lb-file-input flex-between">
            <div :class="[{ 'c-title': subForm.video }]">
              {{ subForm.video | handleFileName }}
            </div>
            <lb-cover type="button" fileType="video" :fileSize="1" @selectedFiles="getFile($event, 'video')"></lb-cover>
          </div>
        </el-form-item> -->
        <el-form-item label="虚拟订单量" prop="order_num">
          <el-input v-model.number="subForm.order_num" placeholder="请输入虚拟订单量"></el-input>
        </el-form-item>
        <el-form-item label="是否接单" prop="is_work">
          <el-radio-group v-model="subForm.is_work">
            <el-radio :label="1">接单</el-radio>
            <el-radio :label="0">休息</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="选择接单时间" prop="start_time" v-if="subForm.is_work">
          <el-time-select placeholder="开始时间" v-model="subForm.start_time" :picker-options="{
              start: '00:00',
              step: '00:01',
              end: '24:00'
            }" style="width: 150px"></el-time-select>
          <block>至{{ subForm | handleStartEndTime }}</block>
          <el-time-select placeholder="结束时间" v-model="subForm.end_time" :picker-options="{
              start: '00:00',
              step: '00:01',
              end: '24:00'
            }" style="width: 150px"></el-time-select>
        </el-form-item>
        <el-form-item label="电子签约：" v-if="
            fdd_agreement &&
            fdd_agreement.id &&
            (routesItem.userInfo.is_admin === 1 ||
              (routesItem.userInfo.is_admin === 0 &&
                routesItem.userInfo.id === subForm.admin_id))
          ">
          <div class="cursor-pointer c-link" @click="showFile = true">
            查看签约合同
          </div>
        </el-form-item>
        <el-form-item :label="'关联' + $t('action.server')" prop="coach"><lb-button type="primary" icon="el-icon-plus"
            @click="toServerShowDialog">选择{{ $t('action.server') }}</lb-button>
          <el-table :data="subForm.server" :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
            class="mt-lg" style="width: 100%">
            <el-table-column prop="id" :label="$t('action.server') + 'ID'"></el-table-column>
            <el-table-column prop="cover" :label="$t('action.server') + '封面'">
              <template slot-scope="scope">
                <lb-image :src="scope.row.cover" />
              </template>
            </el-table-column>
            <el-table-column prop="title" :label="$t('action.server') + '名称'"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <div class="table-operate">
                  <lb-button size="mini" plain type="danger"
                    @click="confirmDel(scope.row.id)">{{ $t('action.delete') }}</lb-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item>
          <lb-button type="primary" @click="submitForm">{{
            $t('action.submit')
          }}</lb-button>
          <lb-button @click="$router.back(-1)">{{
            $t('action.back')
          }}</lb-button>
        </el-form-item>
      </el-form>
      <el-dialog title="关联用户" :visible.sync="showDialog" width="800px" center>
        <lb-tips v-if="routesItem.userInfo.is_admin === 0">请输入服务名称</lb-tips>
        <el-form :inline="true" :model="searchForm" ref="serverSearchForm" label-width="70px">
          <el-form-item label="输入查询" prop="name">
            <el-input v-model="serverSearchForm.name" placeholder="请输入用户名称"></el-input>
          </el-form-item>
          <el-form-item>
            <lb-button size="medium" type="primary" icon="el-icon-search" style="margin-right: 5px"
              @click="getServerTableDataList(1)">{{ $t('action.search') }}</lb-button>
            <lb-button size="medium" icon="el-icon-refresh-left" style="margin-right: 5px"
              @click="resetForm('serverSearchForm')">{{ $t('action.reset') }}</lb-button>
          </el-form-item>
        </el-form>
        <el-table :data="tableData" ref="multipleTable" :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
          tooltip-effect="dark" style="width: 100%" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="id" label="用户ID"></el-table-column>
          <el-table-column prop="avatarUrl" label="头像">
            <template slot-scope="scope">
              <lb-image :src="scope.row.avatarUrl" />
            </template>
          </el-table-column>
          <el-table-column prop="nickName" label="昵称"></el-table-column>
          <el-table-column prop="phone" label="手机号"></el-table-column>
        </el-table>
        <lb-page :batch="false" :page="searchForm.page" :pageSize="searchForm.limit" :total="total"
          @handleSizeChange="handleSizeChange" @handleCurrentChange="handleCurrentChange">
        </lb-page>
        <span slot="footer" class="dialog-footer">
          <el-button @click="showDialog = false">取 消</el-button>
          <el-button type="primary" @click="handleDialogConfirm">确 定</el-button>
        </span>
      </el-dialog>
      <el-dialog title="关联服务" :visible.sync="showServerDialog" width="800px" center>
        <lb-tips v-if="routesItem.userInfo.is_admin === 0">请输入服务名称</lb-tips>
        <el-form :inline="true" :model="searchForm" ref="searchForm" label-width="70px">
          <el-form-item label="输入查询" prop="name">
            <el-input v-model="searchForm.name" placeholder="请输入服务名称"></el-input>
          </el-form-item>
          <el-form-item>
            <lb-button size="medium" type="primary" icon="el-icon-search" style="margin-right: 5px"
              @click="getServerTableDataList(1)">{{ $t('action.search') }}</lb-button>
            <lb-button size="medium" icon="el-icon-refresh-left" style="margin-right: 5px"
              @click="resetForm('searchForm')">{{ $t('action.reset') }}</lb-button>
          </el-form-item>
        </el-form>
        <el-table :data="tableData" ref="multipleTable" :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
          tooltip-effect="dark" style="width: 100%" @selection-change="handleServerSelectionChange">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="id" label="服务ID"></el-table-column>
          <el-table-column prop="cover" label="服务封面">
            <template slot-scope="scope">
              <lb-image :src="scope.row.cover" />
            </template>
          </el-table-column>
          <el-table-column prop="title" label="服务名称"></el-table-column>
          <el-table-column prop="sub_title" label="服务名称简介"></el-table-column>
        </el-table>
        <lb-page :batch="false" :page="serverSearchForm.page" :pageSize="serverSearchForm.limit" :total="total"
          @handleSizeChange="handleSizeChange" @handleCurrentChange="handleCurrentChange">
        </lb-page>
        <span slot="footer" class="dialog-footer">
          <el-button @click="showDialog = false">取 消</el-button>
          <el-button type="primary" @click="handleServerDialogConfirm">确 定</el-button>
        </span>
      </el-dialog>

      <el-dialog title="签约合同" :visible.sync="showFile" :append-to-body="true" width="1000px" center>
        <iframe frameborder="0" :src="fdd_agreement.viewpdf_url" width="100%" height="800px"
          v-if="fdd_agreement && fdd_agreement">
        </iframe>
      </el-dialog>

      <lb-map :dialogVisible.sync="showMap" @selectedLatLng="getLatLng"></lb-map>
    </div>
  </div>
</template>

<script>
  import {
    mapState
  } from 'vuex'
  import moment from 'moment'
  export default {
    data() {
      let checkTime = (rule, value, callback) => {
        let {
          is_work: work = 0,
          start_time: start,
          end_time: end
        } = this.subForm
        if (work && (!start || !end)) {
          callback(new Error(!start ? '请选择开始时间' : '请选择结束时间'))
        } else {
          callback()
        }
      }
      return {
        pickerOptions: {
          disabledDate(time) {
            return time.getTime() > (moment(moment(Date.now()).format('YYYY-MM-DD')).unix() + 24 * 3600 - 1) * 1000
          }
        },
        navTitle: '',
        base_city: [],
        base_store: [],
        showMap: false,
        have_user_id: false,
        fdd_agreement: {},
        subForm: {
          server: [],
          id: 0,
          admin_id: 0,
          admin_name: 0,
          partner_id: 0,
          partner_name: 0,
          user_id: 0,
          nickName: '',
          coach_name: '', // 姓名
          mobile: '', // 手机号
          sex: 0, // 性别
          birthday: '',
          work_time: '', // 从业年份
          city_id: '', // 城市id
          store_id: '', // 门店id
          lng: '',
          lat: '',
          address: '', // 所在地址
          text: '', // 备注
          id_code: '', // 身份证号
          id_card: [], // 身份证
          license: [], // 资格证书
          work_img: [], // 工作照
          self_img: [], // 生活照
          video: '',
          status: 2,
          order_num: 0,
          is_work: 1,
          start_time: '00:00',
          end_time: '23:59',

        },
        subFormRules: {
          coach_name: {
            required: true,
            validator: this.$reg.isNotNull,
            text: this.$t('action.attendantName') + '姓名',
            reg_type: 2,
            trigger: 'blur'
          },
          mobile: {
            required: true,
            validator: this.$reg.isTel,
            text: '手机号',
            reg_type: 2,
            trigger: 'blur'
          },
          sex: {
            required: true,
            type: 'number',
            message: '请选择',
            trigger: 'blur'
          },
          birthday: {
            required: true,
            type: 'number',
            message: '请选择日期',
            trigger: 'blur'
          },
          work_time: {
            required: true,
            type: 'number',
            message: '请输入从业年份',
            trigger: 'blur'
          },
          city_id: {
            required: true,
            type: 'number',
            message: '请选择意向工作城市',
            trigger: 'blur'
          },
          address: {
            required: true,
            type: 'string',
            message: '请输入地址',
            trigger: 'blur'
          },
          lng: {
            required: true,
            validator: this.$reg.isLng,
            trigger: 'blur'
          },
          lat: {
            required: true,
            validator: this.$reg.isLat,
            trigger: 'blur'
          },
          id_code: {
            required: true,
            validator: this.$reg.isIdCard,
            trigger: 'blur'
          },
          text: {
            required: true,
            type: 'string',
            message: '请输入' + this.$t('action.attendantName') + '简介',
            trigger: 'blur'
          },
          id_card: {
            required: true,
            type: 'array',
            message: '请上传图片',
            trigger: 'blur'
          },
          // license: {
          //   required: true,
          //   type: 'array',
          //   message: '请上传图片',
          //   trigger: 'blur'
          // },
          work_img: {
            required: true,
            type: 'array',
            message: '请上传图片',
            trigger: 'blur'
          },
          self_img: {
            required: true,
            type: 'array',
            message: '请上传图片',
            trigger: 'blur'
          },
          order_num: {
            required: true,
            validator: this.$reg.isNum,
            trigger: 'blur'
          },
          is_work: {
            required: true,
            type: 'number',
            message: '请选择',
            trigger: 'blur'
          },
          start_time: {
            required: true,
            validator: checkTime,
            trigger: 'blur'
          }
        },
        searchForm: {
          page: 1,
          limit: 10,
          nickName: ''
        },
        serverSearchForm: {
          page: 1,
          limit: 10,
          name: ''
        },
        total: 0,
        loading: false,
        tableData: [],
        currentRow: {},
        showDialog: false,
        showServerDialog: false,
        showFile: false,
        multipleSelection: []
      }
    },
    async created() {
      let {
        id
      } = this.$route.query
      if (id) {
        this.subForm.id = id
        await this.getDetail(id)
      }
      this.navTitle = this.$t(id ? 'menu.TechnicianEdit' : 'menu.TechnicianAdd')
      this.getBaseInfo()
    },
    computed: {
      ...mapState({
        routesItem: state => state.routes
      })
    },
    methods: {
      async getBaseInfo() {
        let {
          admin_id: aid = 0
        } = this.subForm
        let [city, store] = await Promise.all([this.$api.system.citySelect(), this.$api.technician.storeSelect({
          admin_id: aid
        })])
        this.base_city = city.data
        this.base_store = store.data
      },
      getCover(img, key) {
        this.subForm[key] = img
      },
      getBannerList(imgs, key) {
        this.subForm[key].push(...imgs)
      },
      /**
       * @method 获取经纬度
       */
      getLatLng(latLng) {
        this.subForm.lat = latLng.lat
        this.subForm.lng = latLng.lng
      },
      /**
       * @name: 详情
       * @param {*} id
       */
      async getDetail(id) {
        let {
          code,
          data
        } = await this.$api.technician.coachInfo({
          id
        })
        if (code !== 200) return

        data.nickName = data.user_id ? data.nickName || `用户ID ${data.user_id}`: '';
        data.store_id = data.store_id || ''
        data.birthday = data.birthday ? data.birthday * 1000 : ''
        data.work_img = [{
          url: data.work_img
        }]
        let arr = ['id_card', 'license', 'self_img']
        arr.map((item) => {
          data[item] = data[item] && data[item].length > 0 ? data[item].map((aitem) => {
            return {
              url: aitem
            }
          }) : []
        })
        console.log(555, this.subForm.server)
        for (let key in this.subForm) {
          this.subForm[key] = data[key]
        }
        console.log(666, this.subForm.server, data)
        this.fdd_agreement = data.fdd_agreement
        this.have_user_id = data.id && data.user_id
      },
      getFile(file, key) {
        let len = file.length - 1
        this.subForm[key] = file[len].url
      },
      changeStore(sid) {
        let arr = this.base_store.filter(item => {
          return item.id === sid
        })
        this.subForm.admin_id = arr[0].admin_id
      },
      async toShowDialog() {
        let {
          have_user_id: have
        } = this
        if (have) return
        this.searchForm.nickName = ''
        await this.getTableDataList()
        this.showDialog = !this.showDialog
      },
      async toServerShowDialog() {
        this.searchForm.name = ''
        await this.getServerTableDataList()
        this.showServerDialog = !this.showServerDialog
      },

      resetForm(form) {
        this.$refs[form].resetFields()
        this.getTableDataList(1)
      },
      handleSizeChange(val) {
        this.searchForm.limit = val
        this.handleCurrentChange(1)
      },
      handleCurrentChange(val) {
        this.searchForm.page = val
        this.getTableDataList()
      },
      async getTableDataList(flag) {
        if (flag) this.searchForm.page = 1
        this.loading = true
        let param = JSON.parse(JSON.stringify(this.searchForm))
        let {
          code,
          data
        } = await this.$api.technician.coachUserList(param)
        this.loading = false
        if (code !== 200) return
        this.tableData = data.data
        this.total = data.total
      },
      async getServerTableDataList(flag) {
        if (flag) this.serverSearchForm.page = 1
        this.loading = true
        let param = JSON.parse(JSON.stringify(this.serverSearchForm))
        let {
          code,
          data
        } = await this.$api.service.serviceList(param)
        this.loading = false
        if (code !== 200) return
        this.tableData = data.data
        this.total = data.total
      },
      handleSelectionChange(val) {
        if(val.length > 1){
           this.$message.error(`请选择一个用户`)
           return
        }
        val = val[0];
        let { id, nickName } = val
        val.nickName = nickName || `用户ID ${id}`
        this.currentRow = val
      },
      handleServerSelectionChange(val) {
        console.log(val)
        this.multipleSelection = val
      },
      handleDialogConfirm() {
        if (this.currentRow === null || !this.currentRow.id) {
          this.$message.error(`请选择用户`)
          return
        }
        let { id = 0, nickName = '' } = this.currentRow
        this.subForm.user_id = id
        this.subForm.nickName = nickName
        this.showDialog = false
      },
      handleServerDialogConfirm() {
        let server = this.subForm.server;
        // let arr1 = server.length > 0 ? server.map(item => {
        //   return item.id
        // }) : []
        let arr1 = server.length > 0 ? server.map(item => {
          return item.id
        }) : []
        this.multipleSelection.map(item => {
          if (arr1.includes(item.id)) return
          server.push(item)
        })
        console.log(server)
        this.subForm.server = server
        this.showServerDialog = false
      },
      confirmDel(id) {
        let index = this.subForm.server.findIndex(item => {
          return item.id === id
        })
        this.subForm.server.splice(index, 1)
      },
      /**
       * @name: 新增/编辑
       * @param {*}
       */
      submitForm() {
        let flag = true
        this.$refs['subForm'].validate((valid) => {
          if (!valid) flag = false
        })
        if (flag) {
          let subForm = JSON.parse(JSON.stringify(this.subForm))
          if (subForm.id_card.length < 3) {
            this.$message.error(`身份证照片请分别上传身份证人像面、身份证国徽面、手持身份证照片`)
            return
          }
          subForm.birthday = subForm.birthday / 1000
          let arr = ['id_card', 'license', 'self_img']
          arr.map((item) => {
            subForm[item] = subForm[item].map((aitem) => {
              return aitem.url
            })
          })

          let arr1 = subForm.server.map(item => {
            return item
          })


          subForm.server = arr1
          subForm.work_img = subForm.work_img[0].url
          delete subForm.nickName
          delete subForm.admin_name
          delete subForm.partner_name
          let methodModel = subForm.id ? 'coachDataUpdate' : 'coachAdd'
          this.$api.technician[methodModel](subForm).then((res) => {
            if (res.code === 200) {
              this.$message.success(this.$t(subForm.id ? 'tips.successRev' : 'tips.successSub'))
              this.$router.back(-1)
            }
          })
        }
      }
    },
    filters: {
      handleStartEndTime(val) {
        let text = ''
        let {
          start_time: start,
          end_time: end
        } = val
        let day = moment(Date.now()).format('YYYY-MM-DD')
        if (start && end && (moment(`${day} ${end}`).unix() < moment(`${day} ${start}`).unix())) {
          text = '次日'
        }
        return text
      },
      handleFileName(url) {
        let text = '请上传视频'
        if (url) {
          text = url.substring(url.lastIndexOf('/') + 1)
        }
        return text
      }
    }
  }
</script>

<style lang="scss" scoped>
  .lb-technician-edit {
    width: 100%;

    .el-form {
      width: 100%;

      .el-select,
      .el-input-number,
      .el-input {
        width: 300px;
      }

      .el-textarea {
        width: 600px;
      }

      .el-tag {
        cursor: pointer;
      }
    }
  }
</style>
